<script setup>
import { computed, defineProps, ref } from 'vue'

defineOptions({
  name: 'DictTag',
})

const props = defineProps({
  options: {
    type: Array,
    default: () => [],
  },
  value: [Number, String, Array],
  showValue: {
    type: Boolean,
    default: true,
  },
  separator: {
    type: String,
    default: ',',
  },
  type: {
    type: String,
  },
})

const values = computed(() => {
  const val = props.value
  return val === null || val === undefined || val === ''
    ? []
    : Array.isArray(val)
      ? val.map(String)
      : String(val).split(props.separator)
})

const unmatchArray = ref([])

// 辅助函数，用于检查未匹配的值并更新 unmatchArray
function checkUnmatch() {
  if (props.options.length === 0) {
    return
  }
  const matchedValues = new Set(props.options.map(item => item.value))
  unmatchArray.value = values.value.filter(val => !matchedValues.has(val))
}

// 监听 props.value 或 props.options 的变化来重新检查未匹配的项
watch(() => [props.value, props.options], checkUnmatch)

const hasUnmatch = computed(() => unmatchArray.value.length > 0)

function formatArray(array) {
  return array.join(' ')
}

const unmatchDisplay = computed(() => hasUnmatch.value ? formatArray(unmatchArray.value) : '')
</script>

<template>
  <div>
    <template v-for="item in props.options" :key="item.value">
      <template v-if="values.includes(item.value)">
        <span v-if="item.elTagType === 'default'" :class="item.elTagClass">
          <el-badge is-dot type="primary" class="relative top-[4px] right-[2px]" v-if="type === 'status'" />
          {{ item.label }}
        </span>
        <el-tag v-else :type="item.elTagType" :class="item.elTagClass">
          {{ item.label }}
        </el-tag>
      </template>
    </template>
    <template v-if="props.showValue && unmatchDisplay">
      {{ unmatchDisplay }}
    </template>
  </div>
</template>
